﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Flurl.Http;
using Newtonsoft.Json.Linq;
using Pay.Core;
using Pay.DTO;
using Pay.TO;

namespace Pay.Api.Controllers
{
    public partial class OpenController : BaseController
    {
        /// <summary>
        /// 银行支行
        /// </summary>
        /// <returns>The merchant.</returns>
        /// <param name="model">Model.</param>
        protected ApiPagedResult<bank_number_dto> BranchBank(branch_model model)
        {
            var query = new BranchQuery
            {
                bank_code = model.bank_code,
                city_id = model.city_id,
                name = model.name,
                province_id = model.province_id,
                page = model.page,
                size = model.size
            };
            var list = _iBankNumberService.Get(query);
            var result = new ApiPagedResult<bank_number_dto>(list.rows, list.total_result, list.page, list.size);
            return ApiResultToJson.Json(result);
        }

        /// <summary>
        /// 验证银行卡归属
        /// </summary>
        /// <returns>The vaid.</returns>
        /// <param name="model">Model.</param>
        protected async Task<bank_vail_resp> BankVaid(bank_info_model model)
        {
            if (model.card_type != "DC" && model.card_type != "CC")
            {
                return await ApiResultToJson.JsonAsync<bank_vail_resp>("银行卡不正确");
            }
            string accountNo = model.account_no.Substring(0, 6);
            var bankCode = _iMerchantService.GetBankCode(accountNo, model.card_type);
            if (bankCode == null)
            {
                return await ApiResultToJson.JsonAsync<bank_vail_resp>("未找到该卡信息");
            }

            return await ApiResultToJson.JsonAsync("获取成功", new bank_vail_resp { bank_code = bankCode.Code, bank_name = bankCode.BankName });

        }

        /// <summary>
        /// 请求OSS临时TOEKN，一小时有效
        /// </summary>
        /// <returns>The oss token.</returns>
        protected sts_token GetOssToken(head_req model)
        {
            var merchant = _iMerchantService.Get(model.merchant_no);
            var oss = new OSSToken();
            var oss_set = merchant.setting.oss_set;
            var result = oss.STSToken(oss_set.app_key, oss_set.app_secret, oss_set.arn);
            if (result != null)
            {
                return ApiResultToJson.Json(new sts_token
                {
                    accesskey_id = result.accesskey_id,
                    accesskey_secret = result.accesskey_secret,
                    expiration = result.expiration,
                    token = result.token,
                    bucket_name = oss_set.bucket_name,
                    end_point = oss_set.endpoint
                });
            }
            return ApiResultToJson.Json<sts_token>("请求TOEKN失败");
        }

        /// <summary>
        /// 上传图片，只能post提交
        /// </summary>
        /// <param name="model">对不同上传要求不一样
        /// <para>头像是profile</para>
        /// <para>商品是goods</para>
        /// <para>供应是info</para>
        /// </param>
        /// <returns></returns>
        [Route("upload"), HttpPost, AllowAnonymous]
        public async Task<ApiResultMessage> Upload()
        {
            upload_model model = new upload_model();
            List<string> resources = new List<string>();
            var provider = new MultipartMemoryStreamProvider();
            var task = await Request.Content.ReadAsMultipartAsync(provider);
            string result = string.Empty;
            merchant_dto merchant = null;
            foreach (var item in task.Contents)
            {
                if (item.Headers.ContentDisposition.Name == "data")
                {
                    var data = await item.ReadAsStringAsync();
                    var reqt = JObject.Parse(data);
                    model = reqt.ToObject<upload_model>();
                    merchant = _iMerchantService.Get(model.merchant_no);
                    if (!RSAFromPkcs.verify(ApiSign.sign(reqt), model.sign, merchant.public_key, "utf-8"))
                        return new ApiResultMessage(0, "签名不正确");
                }
                else if (item.Headers.ContentDisposition.FileName != null)
                {
                    //获取到流
                    var ms = await item.ReadAsStreamAsync();
                    using (var br = new BinaryReader(ms))
                    {
                        try
                        {
                            if (ms.Length <= 0) break;
                            string fileName = item.Headers.ContentDisposition.FileName.Replace("\"", "").Replace("\\", "");
                            var dir = model.dir_name;
                            string ext = Path.GetExtension(fileName);
                            //读取文件内容到内存中
                            var file_byte = br.ReadBytes((int)ms.Length);
                            var fileType = FileValid.GetFileType(file_byte);
                            if (fileType != FileExtension.GIF && fileType != FileExtension.JPG && fileType != FileExtension.PNG)
                            {
                                ms.Dispose();
                                return new ApiResultMessage(0, "上传文件格式不正确");
                            }
                            MemoryStream mss = new MemoryStream(file_byte);
                            var oid = Guid.NewGuid().ToString("N");
                            string path = string.Empty;
                            if (!string.IsNullOrEmpty(model.bind_no))
                                path = string.Format("{0}/{1}/{2}{3}", dir, model.bind_no, oid, ext);
                            else
                                path = string.Format("{0}/{1}{2}", dir, oid, ext);
                            var oss_set = merchant.setting.oss_set;
                            var oss = new AliyunOSS(oss_set.key, oss_set.secret, oss_set.endpoint);
                            var ok = oss.PutObject(oss_set.bucket_name, path, mss);
                            if (ok)
                                resources.Add(path);
                            mss.Dispose();
                        }
                        catch (Exception ex)
                        {
                            result = ex.Message;
                        }
                    }
                    if (ms != null)
                        ms.Dispose();
                }
            }

            //释放内存
            GC.Collect();
            //返回
            if (resources.Count == 0)
                return new ApiResultMessage(0, "上传失败");
            else if (resources.Count == 1)
                return new ApiDataResultMessage<string>(resources.First());
            return new ApiDataResultMessage<List<string>>(resources);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns>The file.</returns>
        /// <param name="">.</param>
        protected ApiResultMessage DeleteFile(delete_file_model model)
        {
            var merchant = _iMerchantService.Get(model.merchant_no);
            var oss_set = merchant.setting.oss_set;
            var oss = new AliyunOSS(oss_set.key, oss_set.secret, oss_set.endpoint);
            var count = model.file_names.Count;
            var result = 0;
            foreach (var item in model.file_names)
            {
                bool ok = oss.DeleteObject(oss_set.bucket_name, item.file_name.Trim('/'));
                if (ok) result++;
            }
            if (result > 0)
                return ApiResultToJson.Json(new ApiResultMessage { result_code = 1000, result_msg = "删除成功" });
            return ApiResultToJson.Json<ApiResultMessage>("删除失败");
        }

        /// <summary>
        /// 获取用户指定文件夹的文件
        /// </summary>
        /// <returns>The folder.</returns>
        /// <param name="model">Model.</param>
        protected ApiResultMessage GetFolder(folder_model model)
        {
            var merchant = _iMerchantService.Get(model.merchant_no);
            var oss_set = merchant.setting.oss_set;
            var oss = new AliyunOSS(oss_set.key, oss_set.secret, oss_set.endpoint);
            string folder = model.name + "/" + model.bind_no + "/";
            var list = oss.ListObjects(oss_set.bucket_name, folder);
            return new ApiDataResultMessage<List<oss_bucket_file>>(list);
        }
    }
}
